package com.chagee.store.operation.server.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.TimeInterval;
import com.alibaba.arms.tracing.Span;
import com.alibaba.arms.tracing.Tracer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chagee.store.operation.api.enums.PushFinanceStatusEnum;
import com.chagee.store.operation.api.enums.StoreWorkOrderStatusEnum;
import com.chagee.store.operation.server.entity.StoreSettlementDO;
import com.chagee.store.operation.server.entity.WorkOrderDO;
import com.chagee.store.operation.server.event.dao.WorkOrderMapper;
import com.chagee.store.operation.server.event.service.StoreSettlementBaseService;
import com.chagee.store.operation.server.model.bo.OrderPenalizeBO;
import com.chagee.store.operation.server.service.biz.StoreSettlementBizService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 刷新结算单 结算明细合
 * @Author : hk
 * @Date : 2025/4/14
 */

@Component
@Slf4j
public class RefreshSettlementDetailJobHandler {


	@Resource
	private StoreSettlementBizService storeSettlementBizService;

	@Resource
	private StoreSettlementBaseService storeSettlementBaseService;

	@Resource
	private WorkOrderMapper workOrderMapper;


	/**
	 * 刷新结算单 结算明细合 统计合格工单数
	 * @param param
	 * @return
	 */
	@XxlJob("refreshSettlementDetail")
	public ReturnT<String> refreshSettlementDetail(String param) {
		Span span = Tracer.builder().getSpan();
		TimeInterval timer = cn.hutool.core.date.DateUtil.timer();
		log.info("刷新结算单结算明细合定时任务开始,traceId :{}", span.getTraceId());
		try {
			if (StringUtils.isNotBlank(param)) {
				//结算单号
				List<String> settlementNos = Arrays.stream(param.split(",")).map(String::trim).filter(StringUtils::isNotBlank).collect(Collectors.toList());
				List<StoreSettlementDO> storeSettlementDOS = storeSettlementBaseService.batchSelectSettlement(settlementNos);
				updateSettlementDetail(storeSettlementDOS);
			}else {
				long startIndex = 0L;
				while (true) {
					List<StoreSettlementDO> storeSettlementDOS = storeSettlementBaseService.querySettlements(startIndex);
					if (CollectionUtils.isEmpty(storeSettlementDOS)) {
						break;
					}
					log.info("刷新结算单结算明细合定时任务 :{}", JSON.toJSONString(storeSettlementDOS));

					updateSettlementDetail(storeSettlementDOS);

					startIndex = Math.toIntExact(storeSettlementDOS.stream().map(StoreSettlementDO::getId).max(Comparator.naturalOrder()).orElse(0L));
				}
			}

			log.info("刷新结算单结算明细合定时任务结束，共耗时:{},TraceId:{}", timer.intervalRestart(), span.getTraceId());
		} catch (Exception e) {
			XxlJobLogger.log("刷新结算单结算明细合定时任务异常，异常信息:", e);
			log.error("刷新结算单结算明细合定时任务异常 => param : {} => 异常信息 :", param, e);
		}
		XxlJobLogger.log("刷新结算单结算明细合定时任务结束，共耗时:{},TraceId:{}", timer.intervalRestart(), span.getTraceId());
		return ReturnT.SUCCESS;
	}

	private void updateSettlementDetail(List<StoreSettlementDO> storeSettlementDOS) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
		for (StoreSettlementDO settlementDO : storeSettlementDOS) {

			List<WorkOrderDO> workOrderDOList = workOrderMapper.selectWorkOrderBySupplier(settlementDO.getStoreNo(), simpleDateFormat.format(settlementDO.getSettlementCycle()), settlementDO.getSupplierNo());
			List<WorkOrderDO> collect = workOrderDOList.stream().filter(s -> StoreWorkOrderStatusEnum.COMPLETED.getType().equals(s.getDocumentStatus()) && StringUtils.isNotBlank(s.getDocumentScore()) && Integer.parseInt(s.getDocumentScore()) >= 80).collect(Collectors.toList());

			OrderPenalizeBO orderPenalizeBO = new OrderPenalizeBO();
			if (StringUtils.isNotBlank(settlementDO.getPenalizeMoney())) {
				orderPenalizeBO  = JSON.parseObject(settlementDO.getPenalizeMoney(), new TypeReference<OrderPenalizeBO>() {});
			}
			orderPenalizeBO.setCompletedOrderSize(collect.size());
			settlementDO.setPenalizeMoney(JSON.toJSONString(orderPenalizeBO));
		}

		storeSettlementDOS.forEach(s -> {
			LambdaUpdateWrapper<StoreSettlementDO> wrapper = new LambdaUpdateWrapper<>();
			wrapper.eq(StoreSettlementDO::getId, s.getId());
			wrapper.set(StoreSettlementDO::getPenalizeMoney, s.getPenalizeMoney());
			storeSettlementBaseService.update(wrapper);
		});

	}

}
